<template>
  <div>
    <div>
      <table-btns
        :tableTopOperateData="listData.tableTopOperate"
        :tableTopBatchOperate="listData.tableTopBatchOperate"
        :selectedData="selectedData"
        :requestApi="listData.requestApi"
        :basePath="basePath"
        @exportData="exportData"
        @actionsChange="getData"
      >
      </table-btns>
    </div>
    <!-- 表格内容 start  -->
    <Table
      ref="table"
      :columns="columns"
      :data="tableDataList"
      :loading="loading"
      height='500'
      class="ivu-mt"
      stripe
      border
      @on-filter-change="handleFilterChange"
      @on-select="handleSelect"
      @on-select-cancel="handleSelectCancel"
      @on-select-all="handleSelectAll"
      @on-select-all-cancel="handleSelectAllCancel"
    >
      <template slot-scope="{ row }" slot="auditState">
        <span v-if="row.auditState === '2'">审核通过</span>
        <span v-else-if="row.auditState === '3'">审核未通过</span>
        <span v-else>未审核</span>
      </template>
      <template slot-scope="{ row }" slot="action">
        <a
          v-if="row.canUpdate === '1' && row.brandType === '1' && showBtn('编辑')"
          @click="handleClickAction('edit', row)"
          >编辑</a
        >
      </template>
    </Table>
    <!-- 表格内容 end  -->
    <!-- 分页 start  -->
    <div class="ivu-mt ivu-text-center">
      <Page
        :total="totalNum"
        show-total
        show-sizer
        transfer
        :current.sync="nowPage"
        @on-change="getData"
        @on-page-size-change="handleChangePage"
      />
    </div>
    <!-- 分页 end  -->
    <Modal
      v-model="showProp"
      title="关联分类"
      width="800"
      :fullscreen="true"
      @on-visible-change="visibleChange"
    >
      <Card title="已关联分类">
        <Row
          type="flex"
          class="height30"
          v-for="(item, index) in seletDataList"
          :key="index"
        >
          <Col>{{ item.fullNames }}</Col>
          <div @click="clickDel(item.uuid)">
            <Col>
              <Icon color="red" type="md-close" />
            </Col>
          </div>
        </Row>
      </Card>
      <Card>
        <div>
          <Row type="flex" style="width: 400px">
            <Input
              style="width: 250px"
              search
              enter-button
              placeholder=""
              v-model="searchKey"
              @on-search="inputSub"
            />
            <Button style="margin-left: 8px" @click="reSetSelect">重置</Button>
          </Row>
          <div>
            <Row style="margin-top: 20px" v-if="isSearch">搜索结果：</Row>
            <div v-if="isSearch && inputValue && inputValue.length > 0">
              <Row
                v-for="(item, index) in inputValue"
                :key="index"
                type="flex"
                class="height30"
              >
                <Col>{{ item.fullNames }}</Col>
                <Col style="margin-left: 10px">
                  <Button type="primary" @click="searchRelation(item)"
                    >关联</Button
                  >
                </Col>
              </Row>
            </div>
            <Row v-if="isSearch && inputValue.length == 0">暂无搜索结果</Row>
            <Spin size="large" fix v-if="spinShow"></Spin>
          </div>
        </div>
        <Tree
          ref="tree"
          :data="rootDate"
          :load-data="loadData"
          @on-check-change="treeCheckChange"
          show-checkbox
          check-strictly
          :select-node="false"
          @on-select-change="handleChangeFormData"
        />
      </Card>
      <div slot="footer">
        <Button @click="createRelate('2')">取消</Button>
        <Button type="primary" @click="createRelate('1')">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { mapState, mapMutations, mapGetters } from 'vuex';
import util from '@/libs/util';
import { ApiRequest } from '@api/basePage';
import tables from '@/mixins/dynamictable'; // 混入通用代码
import qwSelect from '@/components/common/formItem/qwSelect'; // 表单select组件
import qwDatePicker from '@/components/common/formItem/qwDatePicker'; // 表单日期组件
import qwSelectTree from '@/components/common/formItem/qwSelectTree'; // 表单下拉树组件
import tableActions from './tableActions'; // 表格操作项
import tableBtns from './tableBtns'; // 表格内部操作按钮
import { getBtnsId } from '@/libs/btnsPermission';

export default {
  mixins: [tables],
  props: {
    dynamicData: {
      type: Object
    },
    pagePath: {
      type: String
    }
  },
  computed: {
    ...mapState('admin/baseList', [
      'listData',
      'searchFormData',
      'searchFormDataQ'
    ]),
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  components: {
    qwSelect,
    qwDatePicker,
    qwSelectTree,
    tableActions,
    tableBtns
  },
  data () {
    return {
      util: util,
      basePath: this.dynamicData.basePath, // 拼接基础路径
      modal1: false,
      loadingSku: false,
      productName: '',
      productNo: '',
      names: 'name1',
      arrList: [],
      arrList1: [],
      labelUuid: '',
      classList: '',
      searchKey: '',
      inputValue: [],
      isSearch: false,
      spinShow: false,
      uuidStr: [],
      data2: [
        {
          title: '全部分类',
          isParent: true,
          children: []
        }
      ],
      value: '',
      actions: [],
      auditModal: false,
      formData: {
        type: [],
        object: []
      },
      aloading: false,
      showProp: false,
      rootDate: [],
      uuid: '', // 当前选中的uuid
      checkData: [],
      seletDataList: [],
      columns12: [
        {
          title: '商品名称',
          key: 'productName'
        },
        {
          title: 'SKU编码',
          key: 'skuNo'
        },
        {
          title: '规格参数',
          key: 'specDetailStr'
        },
        {
          title: '品牌',
          key: 'brandName'
        },
        {
          title: '操作',
          slot: 'action',
          width: 150,
          align: 'center'
        }
      ]
    };
  },
  methods: {
    reSetSelect () {
      this.searchKey = '';
      this.initData();
    },
    ...mapMutations('admin/baseList', ['setTableRowData']),
    // 获取表格的数据
    getData () {
      this.selectedData = [];
      let searchParam = [];
      Object.keys(this.searchFormData).forEach((key) => {
        searchParam.push({
          name: key,
          value: this.searchFormData[key]
        });
      });
      Object.keys(this.searchFormDataQ).forEach((key) => {
        searchParam.push({
          name: key,
          value: this.searchFormDataQ[key]
        });
      });
      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        searchParam: JSON.stringify(searchParam)
      };

      this.loading = true;
      // 开始请求列表
      ApiRequest(
        this.listData.requestApi.getTableList.url,
        this.listData.requestApi.getTableList.type,
        data
      ).then((res) => {
        let rData = res;
        if (rData.retData !== '') {
          rData.retData = rData.retData;
        }
        let tableDataList = rData.retData.results;
        tableDataList.forEach((item) => {
          let actions = [];
          let brandStateMap = {
            1: '启用',
            2: '禁用'
          };
          item.brandStateStr = '未知';
          if (item.brandState) {
            item.brandStateStr = brandStateMap[item.brandState];
          }
          let levelMap = {
            1: '高',
            2: '中高',
            3: '中',
            4: '中低',
            5: '低'
          };
          item.insideLevelStr = '未知';
          if (item.insideLevel) {
            item.insideLevelStr = levelMap[item.insideLevel];
          }
          item.outsideLevelStr = '未知';
          if (item.outsideLevel) {
            item.outsideLevelStr = levelMap[item.outsideLevel];
          }
          item.actions = actions;
        });
        // 增加表格操作项
        this.tableDataList = rData.retData.results;
        this.totalNum = rData.retData.totalNum;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    handleChangeFormData (data, lists) {
      if (!lists.isParent && lists.children.length == 0) {
        let data = {
          brandUuid: lists.uuid
        };
        ApiRequest(
          '/sysback/category/productplatcategoryandbrand/getCateUuidsByBrandUuid',
          'post',
          data,
          true
        ).then((res) => {
          if (res.retStatus === '1') {
            if (res.retData && res.retData.length > 0) {
              for (let i = 0; i < res.retData.length; i++) {
                if (lists.children.length < res.retData.length) {
                  lists['children'].push({
                    title: res.retData[i].categoryName,
                    uuid: res.retData[i].uuid,
                    children: []
                  });
                }
              }
            }
          }
        });
      }
    },
    inputSub (value) {
      if (value) {
        this.spinShow = true;
        this.isSearch = true;
        let data = {
          categoryName: value
        };
        ApiRequest(
          '/sysback/category/productplatformcategory/getByCategoryName',
          'post',
          data,
          true
        ).then((res) => {
          this.spinShow = false;
          if (res.retStatus == '1') {
            if (res.retData.length > 0) {
              this.inputValue = res.retData;
            } else {
              this.inputValue = [];
            }
          }
        });
      } else {
        this.$Message.warning('请输入搜索内容');
      }
    },
    // 模态框显示状态改变时触发
    visibleChange (type) {
      this.inputValue = [];
      this.isSearch = false;
      this.spinShow = false;
      this.searchKey = '';
    },
    // 单个搜索关联分类
    searchRelation (item) {
      this.spinShow = true;
      if (this.labelUuid && item.categoryUuids[item.categoryUuids.length - 1]) {
        let data = {
          brandUuid: this.labelUuid,
          categoryUuid: item.categoryUuids[item.categoryUuids.length - 1]
        };
        ApiRequest(
          '/sysback/category/productplatcategoryandbrand/createSingleRelateBrand',
          'post',
          data,
          true
        ).then((res) => {
          this.spinShow = false;
          if (res.retStatus === '1') {
            this.$Message.success('关联成功');
            // this.showProp = false;
            this.initTopData();
          }
        });
      }
    },
    initTopData () {
      let data = {
        brandUuid: this.labelUuid
      };
      ApiRequest(
        '/sysback/category/productplatcategoryandbrand/getCateUuidsByBrandUuid',
        'post',
        data,
        true
      ).then((res) => {
        this.seletDataList = [];
        if (res.retStatus === '1' && res.retData !== null) {
          // this.seletDataList = res.retData;
          res.retData.forEach((element) => {
            if (element.levelNum === '4') {
              this.seletDataList.push(element);
            }
          });
        } else {
          this.seletDataList = [];
        }
      });
    },
    initData () {
      let data = {
        parentUuid: 'systemUuid'
      };
      ApiRequest(
        '/sysback/category/productplatformcategory/getPlatCategorySubByParentUuidForProduct',
        'post',
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          let myNewData = [];
          res.retData.forEach((item) => {
            myNewData.push({
              title: item.categoryName,
              uuid: item.uuid,
              levelNum: item.levelNum,
              loading: false,
              disableCheckbox: true,
              disabled: true,
              children: []
            });
          });
          this.rootDate = myNewData;
        }
      });
    },

    loadData (item, callback) {
      this._loadData(item.uuid, callback);
    },
    _loadData (code, callback) {
      let data = {
        parentUuid: code
      };
      // 创建分类
      ApiRequest(
        '/sysback/category/productplatformcategory/getPlatCategorySubByParentUuidForProduct',
        'post',
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          let myNewData = [];
          if (res.retData !== null) {
            res.retData.forEach((item) => {
              myNewData.push({
                title: item.categoryName,
                uuid: item.uuid,
                levelNum: item.levelNum,
                disableCheckbox: item.levelNum !== '4',
                disabled: item.levelNum !== '4',
                loading: false,
                checked: item.haveRel === '1',
                children: []
              });
            });
            callback(myNewData);
          } else {
            callback(myNewData);
          }
        }
      });
    },
    treeCheckChange () {
      let sdata = this.$refs.tree.getCheckedNodes();
      let data = [];
      sdata.forEach((item) => {
        data.push(item.uuid);
        this._loadData(item.uuid, (res) => {});
      });
      this.checkData = data;
    },
    createRelate (type) {
      if (type === '1') {
        // 确定
        if (this.checkData === null) {
          this.$Message.error('尚未勾选分类!');
          return false;
        }
        let data = {
          cateUuids: this.checkData.join(','),
          brandUuid: this.uuid
        };
        // 创建分类
        ApiRequest(
          '/sysback/category/productplatcategoryandbrand/createRelateBrand',
          'post',
          data,
          true
        ).then((res) => {
          if (res.retStatus === '1') {
            this.$Message.success('保存成功');
            this.initData();
            this.initTopData();
          }
        });
      } else {
        this.showProp = false;
      }
    },
    clickDel (uuid) {
      let data = {
        platCategoryUuid: uuid,
        brandUuidList: this.uuid
      };
      ApiRequest(
        '/sysback/category/productplatcategoryandbrand/deleteRelation',
        'post',
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          this.$Message.success('删除成功');
          this.initData();
          this.initTopData();
        }
      });
    },
    handleClickAction (type, row) {
      if (type === 'edit') {
        let curBtnId = getBtnsId('编辑');
        sessionStorage.setItem('buttonId', curBtnId);
        let jumpPath = this.basePath + 'Edit';
        this.$router.push({
          path: jumpPath,
          query: {
            pageType: 'edit',
            uuid: row.uuid
          }
        });
      } else if (type === 'del') {
        this.$Modal.confirm({
          title: '删除操作',
          content: '确定删除此数据吗？',
          onOk: () => {
            let curBtnId = getBtnsId('删除');
            sessionStorage.setItem('buttonId', curBtnId);
            let data = {
              uuids: row.uuid
            };
            // 开始请求商品列表
            ApiRequest(
              this.listData.requestApi.delTableList.url,
              this.listData.requestApi.delTableList.type,
              data,
              true
            ).then((res) => {
              if (res.retStatus === '1') {
                this.$Message.success('删除成功');
                this.getData();
              }
            });
          }
        });
      } else if (type === 'prop') {
        let curBtnId = getBtnsId('关联分类');
        sessionStorage.setItem('buttonId', curBtnId);
        this.showProp = true;
        this.uuid = row.uuid;
        this.initData();
        this.initTopData();
        this.labelUuid = row.uuid;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.i-table-no-border .ivu-table-header th {
  background: #f8f8f8;
}

.height30 {
  height: 30px;
  line-height: 30px;
  margin-bottom: 10px;
}
</style>
